﻿using System.Collections;

namespace _12_迭代器模式;

public class Other
{
    public class Main
    {
        public void Show()
        {
            var users = new List<User>()
            {
                new User() { Name = "张三" },
                new User() { Name = "李四" },
                new User() { Name = "王武" },
                new User() { Name = "马六" },
                new User() { Name = "孙奇" },
            };
            UserCollection collection = new UserCollection(users.ToArray());
            while (collection.MoveNext())
            {
                Console.WriteLine(((User)collection.Current).Name);
            }
        }
    }

    /// <summary>
    /// IEnumerator 他就是一个迭代器接口 微软提供
    /// </summary>
    public class UserCollection : IEnumerator
    {
        private readonly User[] _users;

        private int index = 0;

        public object Current { get; private set; }

        public UserCollection(User[] users)
        {
            this._users = users;
        }

        public bool MoveNext()
        {
            if (index > _users.Length - 1)
            {
                return false;
            }

            Current = _users[index++];
            return true;
        }

        public void Reset()
        {
            index = 0;
        }
    }
}

public class User
{
    public string Name { get; set; }
}
